package com.itheima.controller;

import com.itheima.common.JsonResult;
import com.itheima.common.SnowFlake;
import com.itheima.pojo.admin.Pagination;
import com.itheima.pojo.admin.Setmeal;
import com.itheima.pojo.admin.SetmealDish;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ChenJunJie
 * @date 2022/6/13 16:22
 * 分类controller层
 */
@RestController
@RequestMapping(value = "/setmeal", produces = "application/json;charset=utf-8")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SnowFlake snowFlake;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //新增套餐
    @PostMapping
    public JsonResult<String> setmealAdd(@RequestBody Setmeal<SetmealDish> setmeal, HttpServletRequest request) {

        //创建人
        String token = request.getHeader("Authorization");
        String username = redisTemplate.opsForValue().get(token);
        setmeal.setCreateUser(username);

        return setmealService.setmealAdd(setmeal);
    }

    //套餐分页查询
    @GetMapping("/page")
    public JsonResult<Pagination<Setmeal<SetmealDish>>> setmealPagination(String name, @RequestParam("page") Integer page, Integer pageSize) {

        return setmealService.setmealPagination(name,page,pageSize);
    }

    //通过id查询套餐
    @GetMapping("/{id}")
    public JsonResult<Setmeal<SetmealDish>> setmealSelectById(@PathVariable String id){
        return setmealService.setmealSelectById(id);
    }

    //通过套餐id修改套餐
    @PutMapping
    public JsonResult<String> setmealUpdateById(@RequestBody Setmeal<SetmealDish> setmeal,HttpServletRequest request) {

        //修改人
        String token = request.getHeader("Authorization");
        String username = redisTemplate.opsForValue().get(token);
        setmeal.setUpdateUser(username);

        return setmealService.setmealUpdateById(setmeal);
    }

    //通过套餐id删除套餐
    @DeleteMapping
    public JsonResult<String> setmealDeleteById(@RequestParam("ids") String id) {
        boolean b = setmealService.setmealDeleteById(id);

        if (b){
            return JsonResult.success("删除成功");
        }else {
            return JsonResult.error("删除失败");
        }
    }

    //通过套餐id修改套餐状态
    @PostMapping("/status/{status}")
    public JsonResult<String> setmealUpdateStatusById( @PathVariable Integer status ,@RequestParam("ids") String id){
        boolean b = setmealService.setmealUpdateStatusById(status, id);

        if (b){
            return JsonResult.success("修改状态成功");
        }else {
            return JsonResult.error("修改状态失败");
        }
    }
}
